<?php

namespace falcon5\inc\WPProviders;

use Cake\Cache\Cache;
use Exception;
use falcon5\inc\Base\Common;
use falcon5\inc\Base\LanguageAutoSwitch;
use falcon5\inc\Base\WPOption;
use falcon5\inc\Base\ServiceProviderInterface;
use falcon5\inc\Exceptions\UnsupportedLanguageException;
use falcon5\inc\Helpers\FileCacheHelper;
use falcon5\inc\Helpers\UrlHelper;
use falcon5\inc\Infrastructure\Services\CacheService;
use falcon5\inc\Infrastructure\Services\ProxyService;
use GuzzleHttp\Exception\GuzzleException;

/**
 * Class Falcon5Proxy
 * @package falcon5\inc\WPProviders
 * @desc
 */
class Proxy implements ServiceProviderInterface
{

    public function register()
    {
        if (!falcon5_is_rest() && !falcon5_is_proxy()) {
            add_action('init', array($this, 'translation_render'), apply_filters('falcon5_start_output_buffer_priority', 0));
        }
    }

    /**
     * @return void
     * @throws GuzzleException
     */
    function translation_render()
    {
        try {
            /** @var WPOption $falcon5Option */
            $falcon5Option = falcon5_app(WPOption::class);
            $originalLanguage = $falcon5Option->getOriginalLanguage();
            $protocol = UrlHelper::getProtocol();

            /** @var LanguageAutoSwitch $falcon5Switch */
            $falcon5Switch = falcon5_app(LanguageAutoSwitch::class);
            if ($falcon5Switch->checkAutoSwitch()) {
                //auto switch
                $falcon5Switch->autoSwitch();
            }

            // 处理特殊的URL重定向情况
            $url_params = explode('?', $_SERVER['REQUEST_URI']);
            $request_uri = $url_params[0];
            $query_params = $url_params[1] ?? '';

            // 处理子目录模式下的双语言代码重定向
            if (preg_match('/^\\/(' . Common::LANG_PATTERN . ')\\/(' . Common::LANG_PATTERN . ')\\/(.*)$/i', $request_uri, $matches)) {
                $redirectUrl = '/' . $matches[1] . '/' . $matches[3] . ($query_params ? '?' . $query_params : '');
                UrlHelper::redirect($redirectUrl);
            }

            // 处理没有尾部斜杠的语言URL
            if (preg_match('/^\\/(' . Common::LANG_PATTERN . ')$/i', $request_uri)) {
                $redirectUrl = $request_uri . '/' . ($query_params ? '?' . $query_params : '');
                UrlHelper::redirect($redirectUrl);
            }

            // 获取当前URL中的语言信息
            $langInfo = UrlHelper::getUrlInfo();
            $currentLang = UrlHelper::getCurrentLang();

            if ($currentLang) {
                try {
                    if (!in_array($currentLang, $falcon5Option->getAllowedLanguages())) {
                        throw new UnsupportedLanguageException('unsupported lang: ' . $currentLang);
                    }
                    //$ages=[$langInfo['path'],$originalLanguage,$langInfo['lang']];
                    $ages = ["path" => $langInfo['path'], "originalLanguage" => $originalLanguage, "lang" => $langInfo['lang']];
                    do_action(Common::Fc5_TEANSLATION_START_HOOK, $ages);
                    /** @var ProxyService $proxyService */
                    $proxyService = falcon5_app(ProxyService::class);
                    $proxyService->processTranslation(
                        $langInfo['path'],
                        $langInfo['lang'],
                        $originalLanguage,
                        $protocol,
                        $langInfo['mainHost']
                    );
                } catch (Exception $e) {
                    falcon5_error_log('processTranslation: ' . $e->getMessage());
                }
            } else {
                $OPT_FC5_TRANS_MASTER_PAGE_CACHE = $falcon5Option->getOption("FC5_TRANS_MASTER_PAGE_CACHE") ??false;
                if ((defined("FC5_TRANS_MASTER_PAGE_CACHE") && constant("FC5_TRANS_MASTER_PAGE_CACHE") == true) || $OPT_FC5_TRANS_MASTER_PAGE_CACHE) {
                    ob_start(function ($body) {
                        $cacheService = falcon5_app(CacheService::class);
                        $path = UrlHelper::getUrlPathInfo();
                        $filename = $cacheService->getFilename($path, "", "");
                        FileCacheHelper::set($filename, $body);
                        return $body;
                    });
                }
            }
        } catch (Exception $exception) {
            falcon5_error_log('translation_render exception: ' . $exception->getMessage());
        } catch (\Error $error) {
            falcon5_error_log('translation_render error: ' . $error->getMessage());
        }
    }
}
